from typing import List
import random
import pandas as pd

from util.log import Log
from util.redis import Redis
from util.array import Array
from util.time import Time
from util.token import MusicToken
from common.const import BaseConstant

'''
通过收盘价列表，获取 MACD
'''
async def getMACD(closeList: list):
    try:
        res = calculate_macd(closeList)
        return res
    except Exception as e:
        raise e

# close_prices = [0.01577100, 0.01580000, 0.01575000, ...] 收盘价列表
def calculate_macd(close_prices, short=12, long=26, signal=9):
    df = pd.DataFrame({'close': close_prices}) # 将这些收盘价数据组织成一个带有列名 close 的 DataFrame
    df['EMA12'] = df['close'].ewm(span=short, adjust=False).mean()
    df['EMA26'] = df['close'].ewm(span=long, adjust=False).mean()
    df['DIF'] = df['EMA12'] - df['EMA26']
    df['DEA'] = df['DIF'].ewm(span=signal, adjust=False).mean()
    # 不乘 2 也行，币安就是直接相减
    # df['MACD'] = 2 * (df['DIF'] - df['DEA'])
    df['MACD'] = (df['DIF'] - df['DEA'])
    return df[['DIF', 'DEA', 'MACD']]

'''
获取 RSI
'''
async def getRSI(closeList: list):
    try:
        res = calculate_rsi(closeList)
        return res
    except Exception as e:
        raise e

def calculate_rsi(close_prices, period=14):
    df = pd.DataFrame({'close': close_prices})
    # 1. 计算涨跌幅
    df['delta'] = df['close'].diff()
    # 2. 分别计算涨幅和跌幅
    df['U'] = df['delta'].apply(lambda x: x if x > 0 else 0)
    df['D'] = df['delta'].apply(lambda x: -x if x < 0 else 0)
    # 3. 初始的平均涨跌幅（简单平均）
    df['EMA_U'] = df['U'].rolling(window=period, min_periods=1).mean()
    df['EMA_D'] = df['D'].rolling(window=period, min_periods=1).mean()
    # 4. 从第15天开始使用EMA公式更新
    alpha = 1 / period
    for i in range(period, len(df)):
        df.loc[i, 'EMA_U'] = alpha * df.loc[i, 'U'] + (1 - alpha) * df.loc[i - 1, 'EMA_U']
        df.loc[i, 'EMA_D'] = alpha * df.loc[i, 'D'] + (1 - alpha) * df.loc[i - 1, 'EMA_D']
    # 5. 计算RS和RSI
    df['RS'] = df['EMA_U'] / df['EMA_D']
    df['RSI'] = 100 - (100 / (1 + df['RS']))
    return df['RSI']

